package org.dt.common.sequence;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.dt.common.sequence.persist.BaseSeqMapper;
import org.springframework.dao.DuplicateKeyException;

import java.text.MessageFormat;
import java.util.Optional;

/**
 * @author: yujiadong
 * @create: 2019/01/08 13:51
 **/
@Slf4j
@AllArgsConstructor
public abstract class BaseDelegator {
	
    private BaseSeqMapper mapper;

    /**
     * apply for one step from DB
     *
     * @param biz  biz code
     * @param step serial number count
     * @return sequence
     */
    public abstract Sequence applyForOneStep(String biz, long step);

    public void init(String biz) {
        if (Optional.ofNullable(mapper.checkBizItemExists(biz)).orElse(0) == 0) {
            log.info("biz {} 不存在，将自动初始化基础数据", biz);
            try {
                mapper.insert(biz, 0, null);
            } catch (DuplicateKeyException e) {
                log.trace(MessageFormat.format("conflict insert for{0}", biz), e);
            }
        }
    }

}
